package com.moarea.app.service.impl.login;

import com.google.gson.Gson;
import com.moarea.app.lang.model.ResultObject;
import com.moarea.app.lang.utils.StringUtils;
import com.moarea.app.model.LoginUser;
import com.moarea.app.resource.ResourceRepository;
import com.moarea.app.service.abst.ABillBaseService;
import com.moarea.app.service.inter.login.IIndexService;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 首页信息获取控制
 * <p>
 * jizhong
 * <p>
 * 2017-10-26
 */
@Service(value = "indexService")
public class IndexService extends ABillBaseService implements IIndexService {

    /**
     * 获取当前登录用户的信息
     *
     * @param session HttpSession
     * @return ResultObject
     */
    @Override
    public ResultObject obtainLoginUser(HttpSession session) {
        return ResultObject.createInstance(true, "获取成功", (LoginUser) session.getAttribute(ResourceRepository.SESSION_LOGIN_USER));
    }


    /**
     * 用户权限内菜单获取
     *
     * @param param    前端登录参数
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @param session  HttpSession
     * @return 登录结果
     */
    @Override
    public ResultObject obtainUserMenus(Map<String, Object> param, HttpServletRequest request, HttpServletResponse response, HttpSession session) {

        String GUID = (String) session.getAttribute(ResourceRepository.GUID);

        Map<String, String> map = new HashMap<>();
        map.put(ResourceRepository.APPNO, APPNO);
        map.put(ResourceRepository.GUID, GUID);
        map.put(ResourceRepository.USERNO, session.getAttribute(ResourceRepository.USERNO).toString());
        String MENUID;
        String parent = param.get("parent").toString();
        if (StringUtils.isBlank(parent)) {
            MENUID = "1";
        } else {
            MENUID = parent;
        }
        map.put("parent", MENUID);

        //调用UPMS接口登录
        ResultObject resultObject = callHttpAccess(UPMS_URL + "/api/PublicService/obtainUserMenus",
                new Gson().toJson(map), "POST");
        if (!resultObject.isSuccess()) {
            return resultObject;
        }

        //取出访问成功后登录的真实信息
        JSONObject callResult = (JSONObject) resultObject.getData();
        if (!callResult.getBoolean("success")) {
            return ResultObject.createInstance(false, callResult.getString("message"));
        }

        JSONObject callResultData = callResult.getJSONObject("data");
        return ResultObject.createInstance(true, "获取成功", callResultData.get("CHILDREN"));
    }

}
